<template>
  <div class="app-container calendar-list-container">
    <el-dialog :fullscreen="fullscreen" :visible.sync="isShow" width="800px" top="3%" :show-close="false" :before-close="beforeClose">
      <el-row slot="title">
        <el-col :span="10" style="padding-top: 5px">
          <span>{{ WfDecide=='add'?'创建福利':'编辑福利' }}</span>
        </el-col>
        <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
        </el-col>
        <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="parentCloseEvent" style="float: right"></el-button>
        </el-col>
      </el-row>
      <el-form ref="form" :model="form" label-width="90px">
        <el-form-item label="节日名称" prop="holidaywishes_name" :rules="filter_rules({required:true})">
          <el-input clearable style="width: 400px;" placeholder="请输入名称" v-model.trim="form.holidaywishes_name">
          </el-input>
        </el-form-item>
        <el-form-item label="激活条件" prop="activation_condition" :rules="filter_rules({required:true})">
          <el-input clearable style="width: 400px;" placeholder="请输入激活条件" v-model.trim="form.activation_condition">
          </el-input>
        </el-form-item>
        <el-form-item label="发送时间" prop="send_time" :rules="filter_rules({required:true})">
          <el-date-picker style="width: 400px;" v-model="form.send_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请输入发送时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="积分类型" prop="integraltype_id" :rules="filter_rules({required:true})">
          <el-select clearable style="width: 400px;" v-model="form.integraltype_id" placeholder="请选择">
            <el-option v-for="item in classList" :key="item.id" :label="item.label" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="积分数量" prop="score" :rules="filter_rules({required:true})">
          <el-input clearable style="width: 400px;" placeholder="请输入积分数量" v-model.trim="form.score">
          </el-input>
        </el-form-item>
        <!-- 参与人员选则 -->
        <el-form-item label="参与人员选择" label-width="100px"></el-form-item>
        <el-form-item label="组织选择">
            <el-tag v-for="dept in rangeForm.depts" :key="dept.id" style="margin-right:6px;">{{dept.label}}</el-tag>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('dept')"></el-button>
        </el-form-item>
        <el-form-item label="小组选择">
            <el-tag v-for="group in rangeForm.groups" :key="group.id" style="margin-right:6px;">{{group.group_name}}</el-tag>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('group')"></el-button>
        </el-form-item>
        <el-form-item label="人员选择">
            <el-tag v-for="member in rangeForm.members" :key="member.id" style="margin-right:6px;">{{member.user_name}}</el-tag>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('member')"></el-button>
        </el-form-item>
        <!-- 弹框形式 -->
        <el-form-item label="弹框形式选择" label-width="100px"></el-form-item>
        <el-form-item label="系统弹框">
          <el-switch v-model="form.frame_status" active-color="#13ce66" inactive-color="#C0C4CC" 
          active-text="使用系统弹框" inactive-text="不使用系统弹框"></el-switch>
        </el-form-item>
        <el-form-item label="福利封面" prop="picture_path" :rules="filter_rules({type: 'upload'})">
          <el-upload class="avatar-uploader" action="/api/backstage/fileUpload" name="file_path" :show-file-list="false" 
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <div class="img-box" v-if="form.picture_path">
              <img :src="form.picture_path" width="100%" class="avatar">
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p style="color: rgb(245, 108, 108);">建议上传600px*600px的png图片</p>
        </el-form-item>
      </el-form>
      <section>
        <dept-transfer ref="deptInit" @closeTransfer="transfer.deptShow = false" @getDepts="getDepts" :isShow="transfer.deptShow"></dept-transfer>
        <group-transfer ref="groupInit" @closeTransfer="transfer.groupShow = false" @getGroups="getGroups" :isShow="transfer.groupShow"></group-transfer>
        <member-transfer ref="memberInit" @closeTransfer="transfer.memberShow = false" @getMembers="getMembers" :isShow="transfer.memberShow"></member-transfer>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="parentCloseEvent">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { holidaywishes_save, holidaywishes_edit, holidaywishes_findById } from "@/api/holidaywishes";
import { integraltype_listAll } from '@/api/integraltype'
import { mapGetters, mapState } from 'vuex'
import { formateBool } from '@/utils'
import dept_transfer from "@/views/activity/components/add_dept_transfer";
import group_transfer from "@/views/activity/components/add_group_transfer";
import member_transfer from "./add_member_transfer";

export default {
  name:'createTemp',
  props: {
    isShow: Boolean
  },
  components: {
    "dept-transfer": dept_transfer,
    "group-transfer": group_transfer,
    "member-transfer": member_transfer
  },
  computed: {
    ...mapGetters([
        'WfDecide', 'WfEditId'
    ])
  },
  data () {
    return {
      transfer: { deptShow: false, groupShow: false, memberShow:false },
      rangeForm: { depts: [], groups: [], members:[] },
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      fullscreen: false,
      loading: false,
      form:{ picture_path: '' },
      classList: [] //积分类别
    }
  },
  watch: {   //判断是添加时清空数据
    async WfDecide() {
      if (this.WfDecide == "add") {
        this.form = { picture_path: '' };
        this.rangeForm = { depts: [], groups: [], members:[] };
      }
    }
  },
  methods: {
    async clearForm() { 
      this.form = { picture_path: '' };
      this.rangeForm = { depts: [], groups: [], members:[] };
      this.$refs.deptInit.clear();
      this.$refs.groupInit.clear();
      // this.$refs.memberInit.clear();
    },
    beforeClose(e) {
      this.$emit('closeTemp');
    },
    parentCloseEvent() {
      this.$emit('closeTemp');
    },
    openDeptModal(e) { //打开穿梭框组件
      if (e == "dept") {
        this.transfer.deptShow = true;
      }  
      if (e == "group") {
        this.transfer.groupShow = true;
      }
      if (e == "member") {
        this.transfer.memberShow = true;
        this.$refs.memberInit.openTransfer();
      }
    },
    getGroups(e) {  //获取小组
      if (e.length == 0) {
        this.$message.warning("至少要选择一个小组");
        return;
      }
      this.rangeForm.groups = e;
      this.transfer.groupShow = false;
    },
    getDepts(e) { //获取部门
      if (e.length == 0) {
        this.$message.warning("至少要选择一个部门");
        return;
      }
      this.rangeForm.depts = e;
      this.transfer.deptShow = false;
    },
    getMembers(e) { //获取人员
      if (e.length == 0) {
        this.$message.warning("至少要选择一个人员");
        return;
      }
      this.rangeForm.members = e;
      this.transfer.memberShow = false;
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if ( name[name.length - 1] === "jpg" || name[name.length - 1] === "jpeg" || name[name.length - 1] === "png" ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.picture_path = this.ossPublicUrl + "/" + res.data.file_path;
    },
    async validate() {  //校验其他填写的
      let flag = false;
      this.$refs["form"].validate(valid => {
        flag = valid;
        if (!valid) {
          return false;
        }
      });
      return flag;
    },
    async submit(){   //提交数据
      await this.validate();
      if (
        this.rangeForm.groups.length == 0 &&
        this.rangeForm.depts.length == 0 &&
        this.rangeForm.members.length == 0
      ) {
        this.$message.warning("请选择参与人数限制");
        return;
      }
      this.form.frame_status = formateBool(this.form.frame_status);
      let holidaywishesRanges;
      if (this.rangeForm.members) {
        holidaywishesRanges = this.rangeForm.members.map(item => {
          return { range_type: 3, organization_id: item.id };
        });
      }
      if (this.rangeForm.groups) {
        holidaywishesRanges = this.rangeForm.groups.map(item => {
          return { range_type: 2, organization_id: item.id };
        });
      }
      if (this.rangeForm.depts) {
        holidaywishesRanges = this.rangeForm.depts.map(item => {
          return { range_type: 1, organization_id: item.id };
        });
      }
      if (this.rangeForm.groups && this.rangeForm.depts && this.rangeForm.members) {
        let members = this.rangeForm.members.map(item => {
          return { range_type: 3, organization_id: item.id };
        });
        let groups = this.rangeForm.groups.map(item => {
          return { range_type: 2, organization_id: item.id };
        });
        let depts = this.rangeForm.depts.map(item => {
          return { range_type: 1, organization_id: item.id };
        });
        holidaywishesRanges = groups.concat(depts,members);
      }
      this.form.holidaywishesRanges = JSON.stringify(holidaywishesRanges);
      this.WfDecide=='add'?await this.saveObj():await this.editObj();
      await this.clearForm()
    },
    async saveObj() {   //新增福利祝福
      const parms = {...this.form, company_id: localStorage.getItem("companyId") - 0 }
      const { data } = await holidaywishes_save(parms);
      if (data.status == 100) {
          this.$message.success("创建成功")
          this.$emit('closeTemp');
          this.$emit('initList');
      }
    },
    async editObj() {  //修改福利祝福
      const parms = {...this.form, company_id: localStorage.getItem("companyId") - 0 }
      let { data } = await holidaywishes_edit(parms);
      if (data.status == 100) {
          this.$message.success("编辑成功")
          this.$emit('closeTemp');
          this.$emit('initList');
      }
    },
    async initList() {
      this.$nextTick(async _ => {
          this.loading = true
          let { data } = await holidaywishes_findById({ id: this.WfEditId });
          if (data.status == 100) {
            this.form = data.data;
            this.form.frame_status = data.data.frame_status==1?true:false
            this.rangeForm.depts = [];
            this.rangeForm.groups = [];
            this.rangeForm.members = [];
            for (var i = 0; i < data.data.holidaywishesRanges.length; i++) {
              var element = data.data.holidaywishesRanges[i];
              if (element.range_type == 1) {
                this.rangeForm.depts.push({id: element.organization_id, label: element.organization_name });
              } 
              if (element.range_type == 2) {
                this.rangeForm.groups.push({id: element.organization_id, group_name: element.organization_name });
              }
              if (element.range_type == 3) {
                this.rangeForm.members.push({id: element.organization_id, user_name: element.organization_name });
              }
            }
          }
      })
  },
    async initClassList(){  //获取积分类型
      let { data } = await integraltype_listAll({ company_id: localStorage.getItem('companyId') });
      if (data.status == 100) {
        this.classList = data.data.rows.map(item => {
            return { id: item.id, label: item.integraltype_name }
        })
      }
    },
  },
  created () {
    this.initClassList()
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;

.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
}
.avatar {
  width: $picture-size;
  height: $picture-size;
  display: block;
  border-radius: 5px;
}
</style>
